package com.ui.dialog;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TimePicker;

import com.ciko.code.utils.DateUtil;
import com.mywork.R;

public class TimeDateDialog
        extends Dialog
        implements
        View.OnClickListener{
    private DatePicker mDatePicker;
    private TimePicker mTimePicker2;
    String[] minuts = new String[]{"00","30", "00", "30", "00", "30", "00", "30", "00", "30", "00", "30"};
    private Button     timebtn;
    private OnDateTimeClickListener onDateTimeClickListener;
    private Context context;
    int year1;
    int month;
    int day;
    int hour;
    int minute1;

    public TimeDateDialog(Context context,OnDateTimeClickListener onDateTimeClickListener) {
        super(context, R.style.common_dialog);
        this.context = context;
        this.onDateTimeClickListener=onDateTimeClickListener;
        setCanceledOnTouchOutside(true);
        findViews();
        initViews();
        setListeners();
        getWindow().setLayout(ViewPager.LayoutParams.MATCH_PARENT, ViewPager.LayoutParams.WRAP_CONTENT);
        getWindow().setGravity(Gravity.CENTER);
        getWindow().setWindowAnimations(android.R.style.Animation_InputMethod);
    }

    private void initViews() {
        //Calendar是设定年度日期对象和一个整数字段之间转换的抽象基类
        //获取当前年月日
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        /**
         *  init (int year, int monthOfYear, int dayOfMonth,
         *   DatePicker.OnDateChangedListener onDateChangedListener)
         *   将日历初始化为当前系统时间，并设置其事件监听
         */
        mDatePicker.init(year, monthOfYear, dayOfMonth,
                new DatePicker.OnDateChangedListener() {
                    public void onDateChanged(DatePicker view, int year,
                                              int monthOfYear, int dayOfMonth) {
                        //设置标题，注意月份是从0开始的，所以我们在显示的时候要+1
                        setTitle("您选择的日期是：" + year + "年" + (monthOfYear + 1) + "月" + dayOfMonth + "日");
                        year1 = year;
                        month = monthOfYear + 1;
                        day = dayOfMonth;
                    }
                });

        //设置mTimePicker2为24小时制
        mTimePicker2.setIs24HourView(true);
        //设置mTimePicker2初始值为5
        mTimePicker2.setIs24HourView(android.text.format.DateFormat.is24HourFormat(context));
        mTimePicker2.setCurrentHour(0);
        mTimePicker2.setCurrentMinute(0);
        setNumberPickerTextSize(mTimePicker2);
        /**
         * 设置mTimePicker2时间改变事件处理
         * 时间只能取15、30、45
         */
        mTimePicker2.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
//                try {
//                    Field mMinutePicker = view.getClass().getDeclaredField("mMinutePicker");
//                    mMinutePicker.setAccessible(true);
//                    Object value = mMinutePicker.get(view);
//                    Field mCurrent = value.getClass().getDeclaredField("mCurrent");
//                    mCurrent.setAccessible(true);
//                    Field mCurrentMinute = view.getClass().getDeclaredField("mCurrentMinute");
//                    mCurrentMinute.setAccessible(true);
//                    if (minute > 0 && minute < 30) {
//                        mCurrent.set(value, 30);
//                        mCurrentMinute.set(view, 30);
//                    } else {
//                        mCurrent.set(value, 0);
//                        mCurrentMinute.set(view, 0);
//                    }
//                } catch (SecurityException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                } catch (NoSuchFieldException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                } catch (IllegalArgumentException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                } catch (IllegalAccessException e) {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
                hour = hourOfDay;
                if (minute == 0 || minute == 2 || minute == 4 || minute == 6 || minute == 8 || minute == 10) {
                    minute1 = 0;
                } else if (minute == 1 || minute == 3 || minute == 5 || minute == 7 || minute == 9 || minute == 11) {
                    minute1 = 30;
                }
            }
        });

//        DateUtil.StringToDate(year+"-"+(monthOfYear+1)+"-"+dayOfMonth+" "+hourOfDay+":"+minute+":00");
    }

    private List<NumberPicker> findNumberPicker(ViewGroup viewGroup)
    {
        List<NumberPicker> npList = new ArrayList<NumberPicker>();
        View child = null;

        if (null != viewGroup)
        {
            for (int i = 0; i < viewGroup.getChildCount(); i++)
            {
                child = viewGroup.getChildAt(i);
                if (child instanceof NumberPicker)
                {
                    npList.add((NumberPicker)child);
                }
                else if (child instanceof LinearLayout)
                {
                    List<NumberPicker> result = findNumberPicker((ViewGroup)child);
                    if (result.size() > 0)
                    {
                        return result;
                    }
                }
            }
        }

        return npList;
    }

    private void setNumberPickerTextSize(ViewGroup viewGroup){
        List<NumberPicker> npList = findNumberPicker(viewGroup);
        if (null != npList)
        {
            for (NumberPicker mMinuteSpinner : npList)
            {
//            	System.out.println("mMinuteSpinner.toString()="+mMinuteSpinner.toString());
                if(mMinuteSpinner.toString().contains("id/minute")){//�Է��ӽ��м������
                    //android.widget.NumberPicker{42af7a60 VFED.... ......I. 0,0-0,0 #1020499 android:id/minute}
                    mMinuteSpinner.setMinValue(0);
                    mMinuteSpinner.setMaxValue(minuts.length-1);
                    mMinuteSpinner.setDisplayedValues(minuts);  //������ʾ����
                }
                //��Сʱ���м������ ʹ�� if(mMinuteSpinner.toString().contains("id/hour")){}����
                //android.widget.NumberPicker{42af7a60 VFED.... ......I. 0,0-0,0 #1020499 android:id/hour}
            }
        }
    }

    private void findViews() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_time_date, null);
        mDatePicker = (DatePicker) view.findViewById(R.id.mDatePicker);
        mTimePicker2  = (TimePicker)view.findViewById(R.id.mTimPicker2);
        timebtn = (Button) view.findViewById(R.id.time_btn);

        setContentView(view);
    }

    private void setListeners() {
        timebtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (view == timebtn) {
            mDatePicker.clearFocus();
            mTimePicker2.clearFocus();
            if (year1==0&&hour!=0){
                onDateTimeClickListener.yearDay(mDatePicker.getYear(), mDatePicker.getMonth()+1, mDatePicker.getDayOfMonth(),hour,minute1);
                this.dismiss();
                return;
            }
            else if (hour==0&&year1!=0){
                int minute=mTimePicker2.getCurrentMinute();
                if (minute == 0 || minute == 2 || minute == 4 || minute == 6 || minute == 8 || minute == 10) {
                    minute1 = 0;
                } else if (minute == 1 || minute == 3 || minute == 5 || minute == 7 || minute == 9 || minute == 11) {
                    minute1 = 30;
                }
                onDateTimeClickListener.yearDay(year1, month, day,mTimePicker2.getCurrentHour(), minute1);
                this.dismiss();
                return;
            }
            else if (year1==0&&hour==0){
                int minute=mTimePicker2.getCurrentMinute();
                if (minute == 0 || minute == 2 || minute == 4 || minute == 6 || minute == 8 || minute == 10) {
                    minute1 = 0;
                } else if (minute == 1 || minute == 3 || minute == 5 || minute == 7 || minute == 9 || minute == 11) {
                    minute1 = 30;
                }
                onDateTimeClickListener.yearDay(mDatePicker.getYear(), mDatePicker.getMonth()+1, mDatePicker.getDayOfMonth(),mTimePicker2.getCurrentHour(),minute1);
                this.dismiss();
                return;
            }
            else {
                onDateTimeClickListener.yearDay(year1, month, day, hour,minute1);
                this.dismiss();
                return;
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            this.dismiss();
        }
        return super.onKeyDown(keyCode, event);
    }

    public interface OnDateTimeClickListener {
        void yearDay(int year, int month, int day,int hour, int minute);
    }
}
